// pages/index/index.js
import {
    wifiIndexApi,
    commitData,
    getWifi,
    saveContentWifi,
    imguploadapi
} from "../../utils/api"
import utils from "../../utils/util"

let videoAd = null
// 在页面中定义插屏广告
let interstitialAd = null
let flag = true;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        indexData: {},
        show: false,
        bannerAdId1: "adunit-a3b77aaa0c93ed53",
        videoAdId: "adunit-b3eca1b559cff519",
        intAdId: 'adunit-d1829b297ab0c444',
        hasSsidWifi: false,
        shop: {
            name: "",
            phone: "",
            mch_name: "",
            address: "",
            tx_qrcode: ""
        },
        mchInfo: {},
        isNoCommitEd: true,
        showMsg: "",
        img_arr: [],
        isShowBtn: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        const updateManager = wx.getUpdateManager()

        updateManager.onCheckForUpdate(function (res) {
            // 请求完新版本信息的回调
            console.log(res.hasUpdate)
        })

        updateManager.onUpdateReady(function () {
            wx.showModal({
                title: '更新提示',
                content: '新版本已经准备好，是否重启应用？',
                success(res) {
                    if (res.confirm) {
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        updateManager.applyUpdate()
                    }
                }
            })
        })
        const res = await wifiIndexApi()
        if (res.data.code == 200) {
            wx.hideLoading({})
            const resData = res.data.data
            this.setData({
                indexData: resData
            })
        } else {
            wx.hideLoading({})
            utils.wxshowtoast("接口 错误")
        }

        wx.getSetting({
            success(res) {
                if (!res.authSetting['scope.userLocation']) {
                    wx.authorize({
                        scope: 'scope.userLocation',
                        success() {},
                        fail(e) {
                            console.log(e.errMsg)
                            utils.wxshowtoast("请前往授权位置权限，才能正常使用小程序哦~")
                            setTimeout(() => {
                                wx.navigateTo({
                                    url: '/pages/toSetting/toSetting?scene=' + options.scene,
                                })
                            }, 1500)

                        }
                    })
                }
            }
        });

        // 在页面onLoad回调事件中创建插屏广告实例
        if (wx.createInterstitialAd) {
            interstitialAd = wx.createInterstitialAd({
                adUnitId: this.data.intAdId
            })
            interstitialAd.onLoad(() => {})
            interstitialAd.onError((err) => {})
            interstitialAd.onClose(() => {})
        }

        console.log(options)
        // 二维码扫码进入小程序
        var scenearr = decodeURIComponent(options.scene).split(",")
        if (options.scene && scenearr[0] == "wifi") {
            // 后台请求wifi 信息

            const wifiData = await getWifi({
                "wid": scenearr[1]
            });
            if (wifiData.data.code == 200) {
                wx.showLoading({
                    title: '正在搜索可连接wifi',
                })
                const ssid = wifiData.data.data['wifi_ssid'];
                wx.getSystemInfo({
                    success: (res) => {
                        let system = res.system.split(' ')[0]
                        console.log(system)
                        this.startSearchWifi(ssid, wifiData.data.data, system)
                    }
                })

            } else {
                utils.wxshowtoast("获取wifi信息失败，请检查");
                setTimeout(function () {
                    wx.navigateTo({
                        url: '/pages/index/index',
                    })
                    // 在适合的场景显示插屏广告
                    if (interstitialAd) {
                        interstitialAd.show().catch((err) => {})
                    }
                }, 2000)

            }
        }

    },
    async showPopup() {
        if (wx.getStorageSync('openid') == '') {
            wx.navigateTo({
                url: '/pages/login/login',
            })
            return false;
        } else {
            this.setData({
                shop: {},
                isNoCommitEd: true,
                isShowBtn: true
            })
            const info = await commitData('get')
            console.log(info)
            if (info.data.code == 203) {
                this.setData({
                    isNoCommitEd: false,
                    shop: info.data.data,
                    show: true,
                    showMsg: "资料已经提交，等待审核",
                    isShowBtn: false
                })
            } else if (info.data.code == 204) {
                this.setData({
                    isNoCommitEd: false,
                    shop: info.data.data,
                    show: true,
                    showMsg: "已经是商户，修改会重新审核",
                    isShowBtn: false
                })
            } else {
              this.setData({
                isNoCommitEd: true,
                show: true,
                isShowBtn: true
            })
            }
        }

    },
    my_wifi_qrcode() {
        if (wx.getStorageSync('openid') == '') {
            wx.navigateTo({
                url: '/pages/login/login',
            })
            return false;
        } else {
            wx.navigateTo({
                url: '/pages/myWifi/myWifi',
            })
        }

    },
    // 联系人验证
    inputname(e) {
        this.data.shop.name = e.detail.value
        this.setData({
            shop: this.data.shop,
            isShowBtn: true
        })

    },
    //电话号码验证 
    inputphone(e) {
        this.data.shop.phone = e.detail.value
        this.setData({
            shop: this.data.shop,
            isShowBtn: true
        })

    },
    // 店铺验证
    inputstore(e) {
        this.data.shop.mch_name = e.detail.value
        this.setData({
            shop: this.data.shop,
            isShowBtn: true
        })
    },
    // 详细地址验证
    inputstreet(e) {
        this.data.shop.address = e.detail.value
        this.setData({
            shop: this.data.shop,
            isShowBtn: true
        })
    },

    // 商家表单提交
    async commitBtn() {
        if (flag) {
            flag = false
            const res = await commitData('post', this.data.shop)
            if (res.data.code == 200) {
                setTimeout(function () {
                    flag = true;
                }, 1000)
                wx.hideLoading()
                utils.wxshowtoast(res.data.msg)
                this.setData({
                    show: false
                });
            } else {
                setTimeout(function () {
                    flag = true;
                }, 1000)
                wx.hideLoading()
                utils.wxshowtoast(res.data.msg)
            }
        }

    },
    // 获取wifi列表
    startSearchWifi(ssid, wifiData, system) {
        console.log(1)
        wx.startWifi({
            success: (res) => {
                console.log(system === "Android")
                if (system === "Android") {
                    console.log(2)
                    wx.getWifiList({
                        success: (res) => {
                            console.log(3)
                            wx.onGetWifiList(res => {
                                console.log(4)
                                if (res.wifiList.length !== 0) {
                                    console.log(JSON.stringify(res.wifiList))
                                    if (JSON.stringify(res.wifiList).indexOf(ssid) == -1) {
                                        wx.hideLoading({})
                                        utils.wxshowtoast("没有找到指定wifi")
                                    } else {
                                        // 连接wifi
                                        this.connectWifi(wifiData)
                                    }
                                } else {
                                    wx.hideLoading({})
                                    utils.wxshowtoast("你周围没有wifi 哦")
                                }
                            })
                        },
                        fail: (e) => {
                            wx.hideLoading({})
                            switch (e.errCode) {
                                case 12001:
                                    utils.alert("你的手机版本不支持哦~");
                                    break;
                                case 12002:
                                    utils.alert("密码错误~");
                                    break;
                                case 12003:
                                    utils.alert("连接超时~");
                                    break;
                                case 12004:
                                    utils.alert("你已经连接该wifi了~");
                                    break;
                                case 12005:
                                    utils.alert("你的手机未打开wifi开关~");
                                    break;
                                case 12006:
                                    utils.alert("你的手机未打开GPS定位~");
                                    break;
                                case 12007:
                                    utils.alert("用户拒绝连接wifi~");
                                    break;
                                case 12008:
                                    utils.alert("无效wifi名字~");
                                    break;
                                case 12009:
                                    utils.alert("系统运营商配置拒绝连接 Wi-Fi~");
                                    break;
                                case 12010:
                                    utils.alert("系统其他错误~");
                                    break;

                                case 12011:
                                    utils.alert("应用在后台无法配置 Wi-Fi~");
                                    break;

                                case 12013:
                                    utils.alert("系统保存的 Wi-Fi 配置过期，建议忘记 Wi-Fi 后重试~");
                                    break;
                                case 12014:
                                    utils.alert("无效的 WEP / WPA 密码~");
                                    break;

                            }
                        }
                    })
                } else if (system === "iOS") {
                    // ios 直接连接wifi
                    this.connectWifi(wifiData);
                } else {
                    wx.hideLoading({});
                    utils.wxshowtoast("暂不支持你的系统");
                }
            },
            fail: (e) => {
                wx.hideLoading({})
            },
        })
    },

    connectWifi(wifiData) {
        // 在页面onLoad回调事件中创建激励视频广告实例
        if (wx.createRewardedVideoAd) {
            videoAd = wx.createRewardedVideoAd({
                adUnitId: this.data.videoAdId
            })
            videoAd.onLoad(() => {})
            videoAd.show(() => {
                wx.hideLoading({})
            }).catch(err => {
                // 失败重试
                wx.hideLoading({})
                videoAd.load()
                    .then(() => videoAd.show())
            })
            videoAd.onError((err) => {})
            videoAd.onClose((res) => {
                if (res && res.isEnded) {
                    saveContentWifi({
                            "wid": wifiData.id
                        }),
                        wx.connectWifi({
                            SSID: wifiData.wifi_ssid,
                            password: wifiData.wifi_passwd,
                            success: function (res) {
                                wx.getConnectedWifi({
                                    success: (result) => {
                                        if (result.wifi.SSID == wifiData.wifi_ssid) {

                                            utils.wxshowtoast("连接 WiFi: " + wifiData.wifi_ssid + "成功")
                                        } else {
                                            utils.wxshowtoast("连接失败")
                                        }
                                        setTimeout(() => {
                                            if (interstitialAd) {
                                                interstitialAd.show().catch((err) => {})
                                            }
                                        }, 500)
                                    },
                                })
                                return true;
                            },
                            fail: function (e) {
                                wx.getConnectedWifi({
                                    success: (result) => {
                                        if (result.wifi.SSID == wifiData.wifi_ssid) {

                                            utils.wxshowtoast("连接 WiFi: " + wifiData.wifi_ssid + "成功")
                                        } else {
                                            utils.wxshowtoast("连接失败")
                                        }
                                        setTimeout(() => {
                                            if (interstitialAd) {
                                                interstitialAd.show().catch((err) => {})
                                            }
                                        }, 500)
                                    },
                                })
                                return false;
                            }
                        })
                } else {
                    utils.wxshowtoast("放弃就不能连接wifi");
                    return false;
                }
            })
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },
    onClose() {
        this.setData({
            show: false
        });
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    //添加上传图片
    chooseImageTap: function () {
        var that = this;
        wx.showActionSheet({
            itemList: ['从相册中选择', '拍照'],
            itemColor: "#00000",
            success: function (res) {
                if (!res.cancel) {
                    if (res.tapIndex == 0) {
                        that.chooseWxImage('album')
                    } else if (res.tapIndex == 1) {
                        that.chooseWxImage('camera')
                    }
                }
            }
        })
    },
    // 图片本地路径
    chooseWxImage: function (type) {
        var that = this;
        var imgsPaths = that.data.imgs;
        wx.chooseImage({
            sizeType: ['original', 'compressed'],
            sourceType: [type],
            success: function (res) {
                that.upImgs(res.tempFilePaths[0]) //调用上传方法
            }
        })
    },
    //上传服务器
    async upImgs(imgurl) {
        wx.showLoading({title: '上传图片中~'})
        var that = this;
        const data = await imguploadapi(imgurl);
        const res = JSON.parse(data.data)
        
        if (data.statusCode == 200 && res.code == 200) {
          that.data.shop.tx_qrcode = res.data.url
          wx.hideLoading({})
          utils.wxshowtoast("上传完成")
          that.setData({
              shop: that.data.shop,
              isShowBtn: true
          })
        } else {
          wx.hideLoading({})
          if (res.msg) {
            utils.wxshowtoast(res.msg)
          } else {
            utils.wxshowtoast(data.errMsg)
          }
        }
    }
})